package com.itheima.service;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.dubbo.config.annotation.Service;
import com.google.common.collect.Lists;
import com.itheima.dao.OrderSettingMapper;
import com.itheima.pojo.OrderSetting;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Service(interfaceClass = OrderSettingService.class)
@Transactional
public class OrderSettingServiceImpl implements OrderSettingService {

    @Autowired
    OrderSettingMapper orderSettingMapper;

    @Override
    public void setNumberByDate(OrderSetting orderSetting) {
//        1、根据日期查询是否已经存在预约设置数据
        Integer count = orderSettingMapper.findCountByDate(orderSetting.getOrderDate());
        if (count <= 0) {
            //        2、如果不存在那就插入
            orderSettingMapper.add(orderSetting);
        } else {
            //        3、如果存在那就更新
            orderSettingMapper.edit(orderSetting);
        }

    }

    ExecutorService executorService = Executors.newFixedThreadPool(4);

    @Override
    public void setNumberByDateBatch(List<OrderSetting> orderSettings) {

//        for (OrderSetting orderSetting : orderSettings) {
//            setNumberByDate(orderSetting);
//        }

        //思路：可以使用多线程优化，把orderSettings拆分之后给每个线程分配一小份数据
//
//        1、拆分orderSettings
        List<List<OrderSetting>> lists = Lists.partition(orderSettings, 30);

//        2、循环创建线程
        for (List<OrderSetting> list : lists) {
            executorService.submit(new Runnable() {
                @Override
                public void run() {
                    for (OrderSetting orderSetting : list) {//每个线程处理的是一小份数据
                        setNumberByDate(orderSetting);
                    }
                }
            });
        }


    }

    @Override
    public List<Map> findByMonth(String month) {//2020-04
        //[{"date":22,"mouth":3,"number":300,"reservations":300,}] 返回的数据格式

        List<Map> maps = new ArrayList<>();

        String start = month + "-01";
        String end = month + "-31";
        List<OrderSetting> orderSettings = orderSettingMapper.findByMonth(start, end);
        if (CollectionUtil.isNotEmpty(orderSettings)) {
            for (OrderSetting orderSetting : orderSettings) {
                Map map = new HashMap();
                Date orderDate = orderSetting.getOrderDate();
                map.put("date", orderDate.getDate());
                map.put("mouth", orderDate.getMonth());
                map.put("number", orderSetting.getNumber());
                map.put("reservations", orderSetting.getReservations());
                maps.add(map);
            }
        }


        return maps;
    }

    @Override
    public void clearOrderSetting(String nowStr) {
        orderSettingMapper.clearOrderSetting(nowStr);
    }

}

